package com.ruoyi.management.warning.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.ruoyi.adrss.Http;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constant.TaxiConstant;
import com.ruoyi.management.basics.service.ITCarService;
import com.ruoyi.management.basics.service.ITEmployeeService;
import com.ruoyi.management.basics.vo.GetDriverDetailVo;
import com.ruoyi.management.basics.vo.GetDriverVo;
import com.ruoyi.management.rocketmq.TaxiMessage;
import com.ruoyi.management.statistical.carlocaltion.ro.GetCarAddressParam;
import com.ruoyi.management.statistical.carlocaltion.vo.GetWarningCarListVo;
import com.ruoyi.management.warning.domain.TWarning;
import com.ruoyi.management.warning.mapper.TWarningMapper;
import com.ruoyi.management.warning.ro.AddWarningHandleParam;
import com.ruoyi.management.warning.ro.AddWarningParam;
import com.ruoyi.management.warning.ro.GetWarningPageParam;
import com.ruoyi.management.warning.service.ITWarningService;
import com.ruoyi.management.warning.vo.GetWarningPageVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * warningService业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-21
 */
@Service
public class TWarningServiceImpl implements ITWarningService
{
    @Autowired
    private TWarningMapper tWarningMapper;
    @Autowired
    private ITEmployeeService employeeService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITCarService carService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询warning列表
     * 
     * @return warning
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GetWarningPageVo> selectTWarningList(GetWarningPageParam param)
    {
        return tWarningMapper.selectTWarningList(param);
    }

    /**
     * 新增warning
     * 
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTWarning(String userName)
    {
        if(StringUtils.isEmpty(userName)){
            throw new ServiceException("获取当前用户失败，请稍后重试");
        }
        GetDriverVo user = employeeService.getEmployeeByPhone(userName);
        if(null == user){
            throw new ServiceException("获取当前用户失败，请稍后重试");
        }
        //获取实时车辆位置信息
        String address = "";
        String latitude = "";
        String longitude = "";
        String carNo = user.getCarNo();
        if(StringUtils.isEmpty(carNo)){
            throw new ServiceException("获取当前车牌号错误,请稍后重试");
        }
        carNo = CharSequenceUtil.sub(carNo, 1, carNo.length());
        Set<String> allKeys = redisTemplate.keys(CharSequenceUtil.format(TaxiConstant.REAL_TIME_REDIS_KEY, "*","*",carNo,DateUtil.format(new Date(), "yyyyMMdd")));
        List<TaxiMessage> list = redisTemplate.opsForValue().multiGet(allKeys);
        for (TaxiMessage message : list) {
            //纬度
            latitude = message.getLatitude();
            //经度
            longitude = message.getLongitude();
            //获取调用百度地图接口密钥ak
            String ak = configService.selectConfigByKey("ak");
            if (StringUtils.isEmpty(ak)) {
                throw new ServiceException("调用百度地图接口密钥不存在,请联系管理员");
            }
            StringBuilder startUrl = new StringBuilder();
            startUrl.append("https://api.map.baidu.com/reverse_geocoding/v3/?ak=");
            startUrl.append(ak);
            startUrl.append("&output=json&coordtype=wgs84ll&extensions_town=true&location=");
            startUrl.append(latitude);
            startUrl.append(",");
            startUrl.append(longitude);
            address = Http.doGet(startUrl.toString());
        }
        AddWarningParam param = new AddWarningParam();
        param.setCompanyId(user.getCompanyId());
        param.setCompanyName(user.getCompanyName());
        param.setEmployeeId(user.getEmployeeId());
        param.setEmployeeName(user.getEmployeeName());
        param.setCarNo(user.getCarNo());
        param.setPhone(user.getPhone());
        param.setWarningTime(new Date());
        param.setStatus(0);
        if(!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)){
            StringBuilder longitudeLatitude = new StringBuilder();
            longitudeLatitude.append(latitude);
            longitudeLatitude.append(",");
            longitudeLatitude.append(longitude);
            param.setLongitudeLatitude(longitudeLatitude.toString());
            param.setAddress(address);
        }
        int i = tWarningMapper.insertTWarning(param);
        if(i > 0 ){
            String redisKey = CharSequenceUtil.format(TaxiConstant.WARNING_CARNO,carNo);
            redisTemplate.opsForValue().set(redisKey, user.getCarNo());
            String companyKey = CharSequenceUtil.format(TaxiConstant.CAR_COMPANYID,carNo);
            Object companyId = redisTemplate.opsForValue().get(companyKey);
            if(companyId == null){
                companyId = carService.getCompanyIdByCarNo(user.getCarNo());
            }
            String warnCarNumKey = CharSequenceUtil.format(TaxiConstant.WARN_CAR_NUM,companyId);
            redisTemplate.opsForValue().increment(warnCarNumKey, 1);
            String warnAllKey = CharSequenceUtil.format(TaxiConstant.WARN_CAR_NUM_ALL);
            redisTemplate.opsForValue().increment(warnAllKey, 1);
        }
        return i;
    }

    public static void main(String[] args){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = dateFormat.format(date);
        System.out.println(format);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult warningCarAddress(GetCarAddressParam param) {
        AjaxResult ajax = AjaxResult.success();
        String carNo = param.getCarNo();
        carNo = CharSequenceUtil.sub(carNo, 1, carNo.length());
        Set<String> allKeys = redisTemplate.keys(CharSequenceUtil.format(TaxiConstant.REAL_TIME_REDIS_KEY, "*","*",carNo,DateUtil.format(new Date(), "yyyyMMdd")));
        List<TaxiMessage> list = redisTemplate.opsForValue().multiGet(allKeys);
        for (TaxiMessage message : list) {
            //纬度
            String latitude = message.getLatitude();
            //经度
            String longitude = message.getLongitude();
            //获取调用百度地图接口密钥ak
            String ak = configService.selectConfigByKey("ak");
            if(StringUtils.isEmpty(ak)){
                throw new ServiceException("调用百度地图接口密钥不存在,请联系管理员");
            }
            StringBuilder startUrl = new StringBuilder();
            startUrl.append("https://api.map.baidu.com/reverse_geocoding/v3/?ak=");
            startUrl.append(ak);
            startUrl.append("&output=json&coordtype=wgs84ll&extensions_town=true&location=");
            startUrl.append(latitude);
            startUrl.append(",");
            startUrl.append(longitude);
            String address = Http.doGet(startUrl.toString());
            ajax.put("address",address);
            return ajax;
        }
        return AjaxResult.error("获取车辆实时位置失败，请稍后再试");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GetWarningCarListVo> warningCarList(Long companyId) {
        return tWarningMapper.warningCarList(companyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addHandle(AddWarningHandleParam param, Long userId) {
        if(userId == null){
            throw new ServiceException("获取当前用户失败，请稍后重试");
        }
        param.setHandleById(userId);
        param.setHandleByName(sysUserService.getByid(userId));
        param.setHandleTime(new Date());
        int i = tWarningMapper.addHandle(param);
        if(i > 0 ){
            String carNo = param.getCarNo();
            carNo = CharSequenceUtil.sub(carNo, 1,carNo.length());
            String warnKey = CharSequenceUtil.format(TaxiConstant.WARNING_CARNO,carNo);
            redisTemplate.delete(warnKey);
            String companyKey = CharSequenceUtil.format(TaxiConstant.CAR_COMPANYID,carNo);
            Object companyId = redisTemplate.opsForValue().get(companyKey);
            if(companyId == null){
                companyId = carService.getCompanyIdByCarNo(param.getCarNo());
            }
            String warnCarNumKey = CharSequenceUtil.format(TaxiConstant.WARN_CAR_NUM,companyId);
            Object warnCarNumObj = redisTemplate.opsForValue().get(warnCarNumKey);
            if (Objects.nonNull(warnCarNumObj) && (Integer) warnCarNumObj == 0) {
                return i;
            }
            redisTemplate.opsForValue().decrement(warnCarNumKey, 1);
            String warnAllKey = CharSequenceUtil.format(TaxiConstant.WARN_CAR_NUM_ALL);
            Object warnAllObj = redisTemplate.opsForValue().get(warnAllKey);
            if (Objects.nonNull(warnAllObj) && (Integer) warnAllObj == 0) {
                return i;
            }
            redisTemplate.opsForValue().decrement(warnAllKey, 1);
        }
        return i;
    }

}
